package core

import (
	"global/libs/structs"
	"github.com/garyburd/redigo/redis"
	"fmt"
	"global/constants"
)

func GetTickerForSymbolInExchange(conn redis.Conn, exchangeName, symbol string) (*structs.Ticker, error) {
	key := fmt.Sprintf(constants.TickerExchangeKey, exchangeName, symbol)
	v, err := redis.Values(conn.Do("HGETALL", key))
	if err != nil {
		return nil, err
	}

	var t structs.Ticker
	err = redis.ScanStruct(v, &t)
	if err != nil {
		return nil, err
	}

	return &t, nil
}

// 获取Ticker中的某一个字段
func GetItemFromTickerByString(conn redis.Conn, exchangeSlug string, symbol structs.Symbol, itemName string) (string, error) {
	key := fmt.Sprintf(constants.TickerExchangeKey, exchangeSlug, symbol.From + "_" + symbol.To)
	return redis.String(conn.Do("HGET", key, itemName))
}

func SaveTicker(pool *redis.Pool, slug string, tickers []structs.Ticker) error {
	conn := pool.Get()
	defer conn.Close()

	conn.Send("MULTI")
	for _, v := range tickers {
		key := fmt.Sprintf(constants.TickerExchangeKey, slug, v.From + "_" + v.To)
		conn.Send("HMSET", redis.Args{}.Add(key).AddFlat(&v)...)
	}
	_, err := conn.Do("EXEC")
	if err != nil {
		return err
	}
	return nil
}

// 获取 Ticker 信息
func GetTickerBySymbolForExchange(conn redis.Conn, exchangeSlug string, symbol structs.Symbol) (*structs.Ticker, error) {

	key := fmt.Sprintf(constants.TickerExchangeKey, exchangeSlug, symbol.From + "_" + symbol.To)
	exists, err := redis.Bool(conn.Do("EXISTS", key))
	if err != nil {
		return nil, err
	}

	if !exists {
		return nil, fmt.Errorf("key not exists, key %s", key)
	}

	v, err := redis.Values(conn.Do("HGETALL", key))
	if err != nil {
		return nil, err
	}

	var t structs.Ticker
	err = redis.ScanStruct(v, &t)
	if err != nil {
		return nil, err
	}
	return &t, nil
}